<template>
  <div class="model-monitoring">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>模型监控</span>
          <el-button-group>
            <el-button type="primary" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
            <el-button type="warning" @click="handleAlertConfig">
              <el-icon><Bell /></el-icon>告警配置
            </el-button>
          </el-button-group>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 模型性能监控 -->
        <el-tab-pane label="性能监控" name="performance">
          <el-row :gutter="20">
            <!-- 性能指标卡片 -->
            <el-col :span="6" v-for="metric in performanceMetrics" :key="metric.name">
              <el-card class="metric-card" :body-style="{ padding: '20px' }">
                <div class="metric-header">
                  <span class="metric-title">{{ metric.title }}</span>
                  <el-tag :type="metric.status" size="small">{{ metric.statusText }}</el-tag>
                </div>
                <div class="metric-value">{{ metric.value }}</div>
                <div class="metric-chart">
                  <div :ref="el => metric.chartRef = el" class="chart-container"></div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 性能趋势图 -->
          <el-row :gutter="20" class="mt-20">
            <el-col :span="24">
              <el-card class="trend-card">
                <template #header>
                  <div class="card-header">
                    <span>性能趋势</span>
                    <el-radio-group v-model="trendTimeRange" size="small">
                      <el-radio-button label="1h">1小时</el-radio-button>
                      <el-radio-button label="6h">6小时</el-radio-button>
                      <el-radio-button label="24h">24小时</el-radio-button>
                      <el-radio-button label="7d">7天</el-radio-button>
                    </el-radio-group>
                  </div>
                </template>
                <div ref="trendChartRef" class="trend-container"></div>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>

        <!-- 资源监控 -->
        <el-tab-pane label="资源监控" name="resources">
          <el-row :gutter="20">
            <!-- CPU使用率 -->
            <el-col :span="12">
              <el-card class="resource-card">
                <template #header>
                  <div class="card-header">
                    <span>CPU使用率</span>
                    <el-tag type="info" size="small">实时</el-tag>
                  </div>
                </template>
                <div ref="cpuChartRef" class="resource-chart"></div>
              </el-card>
            </el-col>

            <!-- 内存使用率 -->
            <el-col :span="12">
              <el-card class="resource-card">
                <template #header>
                  <div class="card-header">
                    <span>内存使用率</span>
                    <el-tag type="info" size="small">实时</el-tag>
                  </div>
                </template>
                <div ref="memoryChartRef" class="resource-chart"></div>
              </el-card>
            </el-col>
          </el-row>

          <el-row :gutter="20" class="mt-20">
            <!-- GPU使用率 -->
            <el-col :span="12">
              <el-card class="resource-card">
                <template #header>
                  <div class="card-header">
                    <span>GPU使用率</span>
                    <el-tag type="info" size="small">实时</el-tag>
                  </div>
                </template>
                <div ref="gpuChartRef" class="resource-chart"></div>
              </el-card>
            </el-col>

            <!-- 请求延迟 -->
            <el-col :span="12">
              <el-card class="resource-card">
                <template #header>
                  <div class="card-header">
                    <span>请求延迟</span>
                    <el-tag type="info" size="small">实时</el-tag>
                  </div>
                </template>
                <div ref="latencyChartRef" class="resource-chart"></div>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>

        <!-- 告警管理 -->
        <el-tab-pane label="告警管理" name="alerts">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-card class="alert-card">
                <template #header>
                  <div class="card-header">
                    <span>告警列表</span>
                    <el-button-group>
                      <el-button type="primary" @click="handleAddAlert">
                        <el-icon><Plus /></el-icon>添加告警
                      </el-button>
                      <el-button type="danger" @click="handleClearAlerts">
                        <el-icon><Delete /></el-icon>清空告警
                      </el-button>
                    </el-button-group>
                  </div>
                </template>
                <el-table :data="alerts" style="width: 100%">
                  <el-table-column prop="time" label="时间" width="180" />
                  <el-table-column prop="level" label="级别" width="100">
                    <template #default="{ row }">
                      <el-tag :type="getAlertLevelType(row.level)">
                        {{ row.level }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="type" label="类型" width="150" />
                  <el-table-column prop="message" label="告警内容" />
                  <el-table-column prop="status" label="状态" width="100">
                    <template #default="{ row }">
                      <el-tag :type="getAlertStatusType(row.status)">
                        {{ row.status }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                      <el-button-group>
                        <el-button type="primary" link @click="handleViewAlert(row)">
                          查看
                        </el-button>
                        <el-button
                          type="success"
                          link
                          :disabled="row.status === '已处理'"
                          @click="handleProcessAlert(row)"
                        >
                          处理
                        </el-button>
                        <el-button type="danger" link @click="handleDeleteAlert(row)">
                          删除
                        </el-button>
                      </el-button-group>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 告警配置对话框 -->
    <el-dialog
      v-model="alertConfigVisible"
      title="告警配置"
      width="600px"
    >
      <el-form
        ref="alertConfigFormRef"
        :model="alertConfigForm"
        :rules="alertConfigRules"
        label-width="120px"
      >
        <el-form-item label="告警类型" prop="type">
          <el-select v-model="alertConfigForm.type" placeholder="请选择告警类型">
            <el-option label="性能指标" value="performance" />
            <el-option label="资源使用" value="resource" />
            <el-option label="预测延迟" value="latency" />
          </el-select>
        </el-form-item>
        <el-form-item label="告警级别" prop="level">
          <el-select v-model="alertConfigForm.level" placeholder="请选择告警级别">
            <el-option label="严重" value="critical" />
            <el-option label="警告" value="warning" />
            <el-option label="提示" value="info" />
          </el-select>
        </el-form-item>
        <el-form-item label="阈值设置" prop="threshold">
          <el-input-number
            v-model="alertConfigForm.threshold"
            :min="0"
            :max="100"
            :step="1"
          />
        </el-form-item>
        <el-form-item label="告警方式">
          <el-checkbox-group v-model="alertConfigForm.methods">
            <el-checkbox label="email">邮件</el-checkbox>
            <el-checkbox label="sms">短信</el-checkbox>
            <el-checkbox label="webhook">Webhook</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="接收人" prop="receivers">
          <el-select
            v-model="alertConfigForm.receivers"
            multiple
            placeholder="请选择接收人"
          >
            <el-option label="管理员" value="admin" />
            <el-option label="运维人员" value="ops" />
            <el-option label="开发人员" value="dev" />
          </el-select>
        </el-form-item>
        <el-form-item label="告警说明">
          <el-input
            v-model="alertConfigForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入告警说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="alertConfigVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAlertConfigSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import {
  Refresh,
  Bell,
  Plus,
  Delete
} from '@element-plus/icons-vue'

// 标签页
const activeTab = ref('performance')

// 性能监控相关
const performanceMetrics = ref([
  {
    name: 'accuracy',
    title: '准确率',
    value: '95.8%',
    status: 'success',
    statusText: '正常',
    chartRef: null
  },
  {
    name: 'latency',
    title: '平均延迟',
    value: '120ms',
    status: 'warning',
    statusText: '偏高',
    chartRef: null
  },
  {
    name: 'qps',
    title: 'QPS',
    value: '256',
    status: 'success',
    statusText: '正常',
    chartRef: null
  },
  {
    name: 'error_rate',
    title: '错误率',
    value: '0.2%',
    status: 'success',
    statusText: '正常',
    chartRef: null
  }
])

const trendTimeRange = ref('1h')
const trendChartRef = ref(null)
let trendChart = null

// 资源监控相关
const cpuChartRef = ref(null)
const memoryChartRef = ref(null)
const gpuChartRef = ref(null)
const latencyChartRef = ref(null)
let cpuChart = null
let memoryChart = null
let gpuChart = null
let latencyChart = null

// 告警相关
const alerts = ref([
  {
    id: 1,
    time: '2024-03-20 10:30:00',
    level: '严重',
    type: '性能指标',
    message: '模型准确率低于阈值(90%)',
    status: '未处理'
  },
  {
    id: 2,
    time: '2024-03-20 10:15:00',
    level: '警告',
    type: '资源使用',
    message: 'CPU使用率超过80%',
    status: '已处理'
  }
])

const alertConfigVisible = ref(false)
const alertConfigFormRef = ref(null)
const alertConfigForm = reactive({
  type: '',
  level: '',
  threshold: 80,
  methods: [],
  receivers: [],
  description: ''
})

const alertConfigRules = {
  type: [
    { required: true, message: '请选择告警类型', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择告警级别', trigger: 'change' }
  ],
  threshold: [
    { required: true, message: '请设置阈值', trigger: 'change' }
  ],
  receivers: [
    { required: true, message: '请选择接收人', trigger: 'change' }
  ]
}

// 获取告警级别类型
const getAlertLevelType = (level) => {
  const levelMap = {
    '严重': 'danger',
    '警告': 'warning',
    '提示': 'info'
  }
  return levelMap[level] || 'info'
}

// 获取告警状态类型
const getAlertStatusType = (status) => {
  const statusMap = {
    '未处理': 'danger',
    '处理中': 'warning',
    '已处理': 'success'
  }
  return statusMap[status] || 'info'
}

// 初始化图表
onMounted(() => {
  // 初始化性能指标小图表
  performanceMetrics.value.forEach(metric => {
    const chart = echarts.init(metric.chartRef)
    const option = {
      grid: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
      },
      xAxis: {
        type: 'category',
        show: false,
        boundaryGap: false
      },
      yAxis: {
        type: 'value',
        show: false
      },
      series: [{
        data: [30, 40, 35, 50, 49, 60, 70, 91, 125, 80],
        type: 'line',
        smooth: true,
        symbol: 'none',
        areaStyle: {
          opacity: 0.3
        }
      }]
    }
    chart.setOption(option)
  })

  // 初始化性能趋势图
  trendChart = echarts.init(trendChartRef.value)
  const trendOption = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['准确率', '延迟', 'QPS', '错误率']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00']
    },
    yAxis: [
      {
        type: 'value',
        name: '准确率/错误率',
        min: 0,
        max: 100,
        position: 'left'
      },
      {
        type: 'value',
        name: '延迟/QPS',
        position: 'right'
      }
    ],
    series: [
      {
        name: '准确率',
        type: 'line',
        data: [95, 94, 96, 95, 97, 96, 95, 96]
      },
      {
        name: '延迟',
        type: 'line',
        yAxisIndex: 1,
        data: [100, 120, 110, 130, 125, 115, 120, 110]
      },
      {
        name: 'QPS',
        type: 'line',
        yAxisIndex: 1,
        data: [200, 220, 240, 230, 250, 260, 240, 230]
      },
      {
        name: '错误率',
        type: 'line',
        data: [0.5, 0.3, 0.4, 0.2, 0.3, 0.4, 0.5, 0.3]
      }
    ]
  }
  trendChart.setOption(trendOption)

  // 初始化资源监控图表
  const resourceChartOption = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00']
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100
    },
    series: [{
      data: [30, 40, 35, 50, 49, 60, 70, 91],
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      }
    }]
  }

  cpuChart = echarts.init(cpuChartRef.value)
  cpuChart.setOption(resourceChartOption)

  memoryChart = echarts.init(memoryChartRef.value)
  memoryChart.setOption(resourceChartOption)

  gpuChart = echarts.init(gpuChartRef.value)
  gpuChart.setOption(resourceChartOption)

  latencyChart = echarts.init(latencyChartRef.value)
  latencyChart.setOption(resourceChartOption)

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 清理图表实例
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  cpuChart?.dispose()
  memoryChart?.dispose()
  gpuChart?.dispose()
  latencyChart?.dispose()
})

// 处理窗口大小变化
const handleResize = () => {
  trendChart?.resize()
  cpuChart?.resize()
  memoryChart?.resize()
  gpuChart?.resize()
  latencyChart?.resize()
}

// 处理函数
const handleRefresh = () => {
  // TODO: 实现刷新功能
  ElMessage.success('数据已刷新')
}

const handleAlertConfig = () => {
  alertConfigVisible.value = true
  Object.assign(alertConfigForm, {
    type: '',
    level: '',
    threshold: 80,
    methods: [],
    receivers: [],
    description: ''
  })
}

const handleAddAlert = () => {
  // TODO: 实现添加告警功能
  ElMessage.info('添加告警功能开发中...')
}

const handleClearAlerts = () => {
  ElMessageBox.confirm(
    '确定要清空所有告警吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 实现清空告警功能
    ElMessage.success('告警已清空')
  }).catch(() => {})
}

const handleViewAlert = (alert) => {
  // TODO: 实现查看告警功能
  ElMessage.info('查看告警功能开发中...')
}

const handleProcessAlert = (alert) => {
  // TODO: 实现处理告警功能
  ElMessage.success('告警已处理')
}

const handleDeleteAlert = (alert) => {
  ElMessageBox.confirm(
    '确定要删除该告警吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 实现删除告警功能
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleAlertConfigSubmit = async () => {
  if (!alertConfigFormRef.value) return
  
  await alertConfigFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 实现保存告警配置功能
      ElMessage.success('配置已保存')
      alertConfigVisible.value = false
    }
  })
}
</script>

<style scoped>
.model-monitoring {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.metric-card {
  height: 200px;
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.metric-title {
  font-size: 16px;
  font-weight: bold;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.chart-container {
  height: 60px;
}

.trend-card {
  margin-top: 20px;
}

.trend-container {
  height: 400px;
}

.resource-card {
  height: 300px;
}

.resource-chart {
  height: 200px;
}

.alert-card {
  margin-top: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 